/*
Simple Forum Auto Poster.
Copyright (C) 2011 Gianni Van Hoecke.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
package domain.threading;

import domain.DomainController;
import domain.forumdata.Category;
import domain.forumdata.Forum;
import domain.forumdata.Post;
import domain.forumdata.tag.Tag;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

/**
 *
 * @author Gianni Van Hoecke <gianni.vh@gmail.com>
 *
 * This class posts the content to the forums.
 */
public class PosterStarter
{
    private Post post;
    private ArrayList<Forum> theSelectedForums;
    private boolean isQueue;

    /**
     * Default constructor.
     * @param category The category.
     * @param topicTitle The topic title.
     * @param topicSubtitle The topic subtitle or small description.
     * @param tag The tag to use.
     * @param post The message.
     * @param theSelectedForums A list of forums to post to.
     * @param isQueue True means that the user is posting with queued posts, false when posting a single post.
     */
    public PosterStarter(Category category, String topicTitle, String topicSubtitle, Tag tag, String post, ArrayList<Forum> theSelectedForums, boolean isQueue)
    {
        this(new Post(category, topicTitle, topicSubtitle, tag, post), theSelectedForums, isQueue);
    }

    /**
     * Constructor with a Post object.
     * @param post the post to post.
     * @param theSelectedForums A list of forums to post to.
     * @param isQueue True means that the user is posting with queued posts, false when posting a single post.
     */
    public PosterStarter(Post post, ArrayList<Forum> theSelectedForums, boolean isQueue)
    {
        this.post = post;
        this.theSelectedForums = theSelectedForums;
        this.isQueue = isQueue;
    }

    /**
     * Executes the threads.
     */
    public void post()
    {
        DomainController domainController = DomainController.getInstance();
        domainController.resetLastPostTopicURLResults();

        //Calculate progress indicator...
        double adder = 100.0 / (double)theSelectedForums.size();
        if(this.isQueue)
            adder /= (double)domainController.getQueue().getQueue().size();

        //Create poster object...
        ArrayList<Poster> threads = new ArrayList<Poster>();
        for(Forum forum : this.theSelectedForums)
        {
            threads.add(new Poster(post, forum, adder));
        }

        //Create a thread pool
        ExecutorService exec = Executors.newFixedThreadPool(domainController.getPreferences().getBatchPostThreads());

        //Add the poster objects to the pool and start.
        for(Poster poster : threads)
        {
            exec.execute(poster);
        }

        //Stop accepting new threads.
        exec.shutdown();

        //Wait until the ExecutorService has finished his jobs...
        try
        {
            while (!exec.awaitTermination(2, TimeUnit.SECONDS))
            {
                //Wait...
            }
        }
        catch(Exception e)
        {
            domainController.getLogger().log(Level.SEVERE, e.getMessage());
        }

        //Save to history.
        Post pOld = domainController.getHistory().getExactPost(this.post);

        if(pOld == null)
        {
            //This post is unique, just add it.
            this.post.getTopicURLResults().addAll(domainController.getLastPostTopicURLResults());
            domainController.getHistory().getHistory().add(this.post);
        }
        else
        {
            //This post has already been used, so update date and add new urls.
            pOld.getTopicURLResults().addAll(domainController.getLastPostTopicURLResults());
            pOld.updatePost();
        }

        domainController.saveHistory();
        domainController.loadHistoryUI();
        
        //Done.
        if(!this.isQueue)
        {
            domainController.updateProgress(100, "Ready");
            domainController.getUi().setButtonsEnabled(true);
            domainController.getUi().fireDone();
        }
    }
}